package freakin.wify;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.IBinder;
import android.util.Log;

public class WifiService extends Service {

	private static final String TAG = "WifiService";

	WifiManager wifi;
	WifiLock lock;
	BroadcastReceiver receiver;
	WifiApp app;
	Updater updater;

	private boolean wifiActive;

	protected boolean serviceActive;

	public void onCreate() {
		app = (WifiApp) getApplication();

		Log.d(TAG, "created service");
	}

	public IBinder onBind(Intent arg0) {
		return null;
	}

	public void start() {

		// nie ma sprawdzania, czy wifi jest wlaczone, czy nie.
		// jak nie jest - to trudno, zucyjemy troche RAMu nadaremnie.

		setUpWifi();

		registerReceiver(receiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

		serviceActive = true;
		app.startService();

		updater = new Updater();
		updater.start();

		Log.d(TAG, "start(). serviceActive = " + serviceActive
				+ ". Is wifi enabled? = " + wifiActive);

	}

	public void stop() {
		unregisterReceiver(receiver);
		serviceActive = false;
		updater.interrupt();
		updater = null;
		app.stopService();
		lock.release();

		Log.d(TAG, "stop(). serviceActive = " + serviceActive);
	}

	private void setUpWifi() {
		// Setup WiFi
		wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

		lock = wifi.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY,
				"wify_scan_lock");

		lock.acquire();
		wifiActive = wifi.isWifiEnabled();

		// Register Broadcast Receiver
		if (receiver == null)
			receiver = new WifiScanReceiver(this, app.nm);

		Log.d(TAG, "setUpWifi(). Wifi is currently active? " + wifiActive);
	}

	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		if (intent.getFlags() == WifyActivity.STATUS_CHANGE) {
			Log.d(TAG, "changing service status");

			if (serviceActive)
				stop();
			else
				start();

		}
		return Service.START_STICKY;
	}

	private class Updater extends Thread {

		private static final String TAG = "WifiService.Updater";

		public Updater() {
			super("Updater-of-WifiService");
			Log.d(TAG, "created Updater");
		}

		public void run() {
			while (app.serviceActive) {
				try {
					Log.d(TAG, "Updater running... scanning networks");
					
					Log.d(TAG, "startScan() returned: " + wifi.startScan());

					Thread.sleep(app.scanInterval);
				} catch (InterruptedException ie) {
					Log.e(TAG, "interrupted Updater thread");
					ie.printStackTrace();
				}
			}
		}

	}

}
